<template>
  <div>
    <!-- 按钮组件 -->
    <el-button
      type="primary"
      icon="el-icon-plus"
      style="margin: 10px 0px"
      @click="showDialog"
      >添加</el-button
    >
    <!-- 表格组件 -->
    <!-- data：表格组件将来需要显示的数据--数组类型
            border：给表格添加边框
            label：设置标题
            width：对应列的宽度
            align：标题的对齐方式 -->
    <!-- 注意：数据是一列一列展示的 -->
    <el-table style="width: 100%" border :data="list">
      <!-- el-table-column：代表一列 -->
      <el-table-column type="index" label="序号" width="80px" align="center">
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width">
      </el-table-column>
      <el-table-column prop="logoUrl" label="品牌LOGO" width="width">
        <template slot-scope="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{ row }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            @click="updateTradeMark(row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteTradeMark(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器组件 -->
    <!-- 当前第几页、数据总数、每一页展示条数、连续页码数 
        @size-change="handleSizeChange":pageSize 每一页展示条数改变时会触发
      @current-change="handleCurrentChange":currentPage 改变时会触发-->
    <!-- layout:组件布局，子组件名用逗号分隔 
           pager-count:页码按钮的数量，间接设置连续页码数-->
    <el-pagination
      style="margin-top: 20px; text-align: center"
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[3, 5, 10]"
      :pager-count="7"
      layout="prev,pager,next,jumper,->,sizes,total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>

    <!-- 对话框组件 -->
    <!-- :visible.sync：控制对话框显示和隐藏 -->
    <el-dialog
      :title="tmForm.id ? '修改品牌' : '添加品牌'"
      :visible.sync="dialogFormVisible"
    >
      <!-- form表单 -->
      <el-form style="width: 80%" :model="tmForm" :rules="rules" ref="ruleForm">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input autocomplete="off" v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!-- action：设置图片上传的地址
                on-success:图片上传成功会执行一次
                before-upload:图片上传之前会执行一次 -->
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "TradeMark",
  data() {
    // 自定义校验规则
    var validatePass = (rule, value, callback) => {
      if (value.length < 2 || value.length > 10) {
        callback(new Error("品牌名称2-10位"));
      } else {
        callback();
      }
    };
    return {
      page: 1, //第几页
      limit: 3, //每页展示多少条数据
      total: 0, //总数
      list: [], //列表展示的数据
      dialogFormVisible: false, //控制对话框显示和隐藏
      imageUrl: "", //上传图片使用的属性
      tmForm: {
        //收集品牌信息:对象身上的属性不能瞎写，需要看文档
        tmName: "",
        logoUrl: "",
      },
      rules: {
        // 品牌名称的验证规则
        // trigger：用户行为设置（blur、change）
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          // { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "change"}
          // 自定义校验
          { validator: validatePass, trigger: "change" },
        ],
        // 品牌logo的验证规则
        logoUrl: [{ required: true, message: "请选择品牌图片" }],
      },
    };
  },
  mounted() {
    this.getPageList();
  },
  methods: {
    async getPageList() {
      const { page, limit } = this;
      let result = await this.$API.trademark.reqTradeMarkList(page, limit);
      console.log(result, "获取品牌管理数据");
      if (result.code == 200) {
        this.total = result.data.total;
        this.list = result.data.records;
      }
    },
    handleCurrentChange(pager) {
      this.page = pager;
      this.getPageList();
    },
    handleSizeChange(limit) {
      this.limit = limit;
      this.getPageList();
    },
    // 点击添加品牌
    showDialog() {
      this.dialogFormVisible = true; // 显示对话框
      this.tmForm = { tmName: "", logoUrl: "" }; //清空数据
    },
    // 修改某个品牌
    updateTradeMark(row) {
      this.dialogFormVisible = true; // 显示对话框
      // row是当前用户选中品牌的信息
      console.log(row, "row");
      this.tmForm = { ...row }; //浅拷贝
    },
    // 上传图片相关的回调
    handleAvatarSuccess(res, file) {
      // res是上传成功后返回给前端的数据
      console.log(res, "res");
      this.tmForm.logoUrl = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 添加按钮——添加或修改
    addOrUpdateTradeMark() {
      // 当全部验证字段通过再去书写业务逻辑
      this.$refs.ruleForm.validate(async (success) => {
        if (success) {
          this.dialogFormVisible = false;
          // 发请求——添加或修改
          let result;
          try {
            result = await this.$API.trademark.reqAddOrUpdateTradeMark(
              this.tmForm
            );
            console.log(result, "添加/修改品牌成功");
          } catch (error) {
            result = error;
            console.log(result, "添加/修改品牌失败");
          }
          if (result.code == 200) {
            // 弹出信息:添加/修改品牌成功
            this.$message({
              type: "success",
              message: this.tmForm.id ? "修改品牌成功" : "添加品牌成功",
            });
            // 如果添加品牌，停留在第一页，如果修改品牌应该留在当前页
            this.getPageList(this.tmForm.id ? this.page : 1);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 删除品牌操作
    deleteTradeMark(row) {
      // 弹框
      this.$confirm(`确定删除${row.tmName}？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 当用户点击确定按钮时会触发
          // 向服务器发请求
          let result;
          try {
            result = await this.$API.trademark.reqDeleteTradeMark(row.id);
            console.log(result, "删除品牌成功");
          } catch (error) {
            result = error;
            console.log(result, "删除品牌失败");
          }
          if (result.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            // 再次获取品牌列表数据
            this.getPageList(this.List.length > 1 ? this.page : this.page - 1);
          }
        })
        .catch(() => {
          // 当用户点击取消按钮时触发
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>